/**
 * Created by Yao on 2018/8/6.
 */
// var userName = $.fn.cookie('medtion_member_username');
// var meeting_isLogin=$.fn.cookie("meeting_isLogin");
// var weixinLogin=function (unionid) {
//     var isSuccess=false;
//     $.ajax({
//         type: 'post',
//         url: '/h5WeixinLogin.jspx',
//         data: {
//             unionid: unionid
//         },
//         dataType: 'json',
//         async: false,
//         success: function (resp) {
//             var code=resp.code;
//             if(code==1){
//                 isSuccess=true;
//                 var userStr = resp.data;
//
//                 $.fn.cookie("medtion_member_username", userStr.username, {expires: 1000, path: '/'});
//                 $.fn.cookie("medtion_member_realName", userStr.realName, {expires: 1000, path: '/'});
//                 $.fn.cookie("medtion_member_empcard", userStr.avatarAddress, {expires: 1000, path: '/'});
//                 $.fn.cookie("medtion_member_id", userStr.id, {expires: 1000, path: '/'});
//                 $.fn.cookie("medtion_member_isAuth", userStr.isAuth, {expires: 1000, path: '/'});
//             }
//         },
//         error:function () {
//             isSuccess=true;
//         }
//     });
//     return isSuccess;
// };
// //判断是否已绑定
// var isExist=function (unionid) {
//
//     var flag=false;
//
//     $.ajax({
//         type: 'get',
//         url: '/isUnionidExist.jspx',
//         data: {
//             unionid: unionid
//         },
//         dataType: 'json',
//         async: false,
//         success: function (resp) {
//             if(resp){
//                 flag=true;
//             }else{
//                 flag=false;
//             }
//
//         },
//         error:function () {
//             flag=false;
//         }
//     });
//     return flag;
//
//
// };
// var redirectUrl=document.location.href;
//
// if(redirectUrl.indexOf("code="+code)!=-1){
//     redirectUrl=redirectUrl.replace("code="+code,"");
// }
// if(userAgent) {
//     //判断是否在微信内打开，微信内打开则获取授权unionid
//     if (userAgent.toLowerCase().indexOf('micromessenger') !== -1) {
//         if(meeting_isLogin!="F"){
//             $.fn.cookie("meeting_isLogin", "", {expires: 1000, path: '/'});
//             if(!userName){
//
//                 if(!isExist(unionid)){
//                     alert("unionid     :"+unionid)
//                     //未绑定微信则先跳转至登录页
//                     location.href="/h5MemberLoginEntrance.jspx?backurl="+redirectUrl;
//                     // throw "已跳转，停止加载"
//                     window.event.returnValue=false;
//                 }else{
//                     if(weixinLogin(unionid)){
//                         console.log("登录成功");
//                         location.href=redirectUrl;
//                         window.event.returnValue=false;
//                         // throw "已跳转，停止加载"
//                     }
//                 }
//             }
//         }
//
//
//     }
// }
export function wxlogin (queryString) {
  console.log(queryString)
  var $ = {}
  var getParameter = function (queryString, name) {
    queryString = queryString.replace(/from=singlemessage&/, '').replace(/&from=singlemessage/, '').replace(/from=singlemessage/, '')
    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
    var r = queryString.substr(1).match(reg)
    if (r) {
      return decodeURI(r[2])
    } else {
      return null
    }
  }

  // var meeting_isLogin = $.fn.cookie("meeting_isLogin");
  var code = getParameter(window.location.search, 'code')
  var userAgent = navigator.userAgent
  var unionid = $.fn.cookie('unionid')
  var userName = $.fn.cookie('medtion_member_username')

  // 获取unionid
  var getUnionid = function (code) {
    // alert("code值已经取到");
    var unionid = ''
    $.ajax({
      type: 'get',
      url: '/wxmp/getOpenIdAndAccessToken.jspx',
      data: {
        code: code
      },
      dataType: 'json',
      async: false,
      success: function (resp) {
        if (resp.code === 1) {
          // alert("已经获取unionid");
          unionid = resp.data.unionid
          $.fn.cookie('unionid', resp.data.unionid, { expires: 1000, path: '/' })
        } else {
          unionid = ''
        }
      },
      error: function () {
        return ''
      }
    })
    return unionid
  }

  // 微信自动登录
  var weixinLogin = function (unionid) {
    var isSuccess = false
    $.ajax({
      type: 'post',
      url: '/h5WeixinLogin.jspx',
      data: {
        unionid: unionid
      },
      dataType: 'json',
      async: false,
      success: function (resp) {
        var code = resp.code
        if (code === 1) {
          isSuccess = true
          var userStr = resp.data

          $.fn.cookie('medtion_member_username', userStr.username, { expires: 1000, path: '/' })
          $.fn.cookie('medtion_member_realName', userStr.realName, { expires: 1000, path: '/' })
          $.fn.cookie('medtion_member_empcard', userStr.avatarAddress, { expires: 1000, path: '/' })
          $.fn.cookie('medtion_member_id', userStr.id, { expires: 1000, path: '/' })
          $.fn.cookie('medtion_member_isAuth', userStr.isAuth, { expires: 1000, path: '/' })
        }
      },
      error: function () {
        isSuccess = true
      }
    })
    return isSuccess
  }
  // 判断是否已绑定
  var isExist = function (unionid) {
    var flag = false

    $.ajax({
      type: 'get',
      url: '/isUnionidExist.jspx',
      data: {
        unionid: unionid
      },
      dataType: 'json',
      async: false,
      success: function (resp) {
        if (resp) {
          flag = true
        } else {
          flag = false
        }
      },
      error: function () {
        flag = false
      }
    })
    return flag
  }

  // eslint-disable-next-line camelcase
  var meeting_isLogin = 'F'

  // 根据条件判断是否执行登录
  var execLogin = function (userAgent, unionid) {
    if (userAgent) {
      // 判断是否在微信内打开，微信内打开则获取授权unionid
      if (userAgent.toLowerCase().indexOf('micromessenger') !== -1) {
        if (!userName) {
          var redirectUrl = document.location.href

          if (redirectUrl.indexOf('code=' + code) !== -1) {
            redirectUrl = redirectUrl.replace('code=' + code, '')
          }
          if (!isExist(unionid)) {
            // eslint-disable-next-line camelcase
            if (meeting_isLogin !== 'F') {
              // alert("需要登录")
              $.fn.cookie('meeting_isLogin', '', { expires: 1000, path: '/' })
              // 未绑定微信则先跳转至登录页
              location.href = '/h5MemberLoginEntrance.jspx?backurl=' + redirectUrl
            }

            // throw "已跳转，停止加载"
          } else {
            if (weixinLogin(unionid)) {
              console.log('登录成功')
              location.href = redirectUrl
              // throw "已跳转，停止加载"
            }
          }
        }
      }
    }
  }

  var getCode = function (userAgent) {
    if (userAgent) {
      // 判断是否在微信内打开，微信内打开则获取授权unionid
      if (userAgent.toLowerCase().indexOf('micromessenger') !== -1) {
        // 若用户未登录则获取unionid
        if (!userName) {
          if (!unionid) {
            // 若unionid为空，获取unionid
            if (!code) {
              // 没有code重新获取code
              // alert("跳转之前");
              location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx39e8149ff76f5464&redirect_uri=' + encodeURIComponent(document.location.href) + '&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect'
            } else {
              if ($.fn.cookie('code')) {
                // eslint-disable-next-line eqeqeq
                if (code == $.fn.cookie('code')) {
                  var url = document.location.href

                  // eslint-disable-next-line eqeqeq
                  if (url.indexOf('code=' + code) != -1) {
                    url = url.replace('code=' + code, '')
                  }
                  location.href = url
                  return
                } else {
                  $.fn.cookie('code', code, { expires: 1000 })
                }
              } else {
                $.fn.cookie('code', code, { expires: 1000 })
              }
              unionid = getUnionid(code)
              execLogin(userAgent, unionid)
            }
          }
        }
      }
    }
  }
  if (!unionid) {
    getCode(userAgent)
  } else {
    execLogin(userAgent, unionid)
  }
}
